package com.zb.netty.chat.server.handler;

import java.lang.reflect.Method;

import com.zb.netty.chat.message.RpcRequestMessage;
import com.zb.netty.chat.message.RpcResponseMessage;
import com.zb.netty.chat.server.service.ServicesFactory;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author: zhaobin
 * @date: 2024/6/25 20:36
 * @Description:
 */
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage message){
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        responseMessage.setSequenceId(message.getSequenceId());//将请求序列号存储到响应对象中
        Class<?> clazz = null;
        Method method = null;
        Object returnVal = null;
        try {
            clazz = Class.forName(message.getInterfaceName());
            method = clazz.getMethod(message.getMethodName(), message.getParameterTypes());
            returnVal = method.invoke(ServicesFactory.getService(clazz), message.getParameterValue());
            //运行成功设置值
            responseMessage.setReturnValue(returnVal);
            System.out.println(responseMessage);
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常封装好异常信息后传出
            responseMessage.setExceptionValue(new Exception("远程调用出错："+e.getCause().getMessage()));
        }
        ctx.channel().writeAndFlush(responseMessage);
    }

}
